package com.ruoyi.web.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sns")
public class SnsLoginController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SysLoginService sysLoginService;

    @GetMapping("/authorize/{platformName}")
    public void authorize(@PathVariable String platformName, HttpServletResponse response) throws Exception {
       response.sendRedirect("https://gitee.com/oauth/authorize?client_id=25ba51f96202c8f6f6ab70e5483f59923641c3f9f931e0fcb03ef8dee6d7663b&redirect_uri=http://localhost:81/login&response_type=code");
    }

    //git同意授权后跳转登录页面带code，有code跳此
    @GetMapping("/{platformName}/snsLogin")
    public AjaxResult snsLogin(@PathVariable String platformName,String code){
        System.out.println(code);
        //1.根据授权码code获取token
        String url="https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&code=" +code+
                "&client_id=25ba51f96202c8f6f6ab70e5483f59923641c3f9f931e0fcb03ef8dee6d7663b" +
                "&redirect_uri=http://localhost:81/login" +
                "&client_secret=f9ceb414f763358156b525f4add2191cba25fa1c9a8ffa1ffff1678d711d0adc";
          Map map=restTemplate.postForObject(url,null,Map.class);
        String accessToken=(String)map.get("access_token");
        //2.根据token获取用户信息
            String userInfoUrl="https://gitee.com/api/v5/user?access_token="+accessToken;
        Map userinfo = restTemplate.getForObject(userInfoUrl, Map.class);
        System.out.println("userinfo = " + userinfo);
        String loginName=platformName+"_"+userinfo.get("login");
        String nickName=(String)userinfo.get("name");
        //4.进行本系统若一登录，创建一个用户登录若一
      AjaxResult ajaxResult=AjaxResult.success();
      //生成令牌
      String token=sysLoginService.snslogin(loginName,nickName);
      ajaxResult.put(Constants.TOKEN,token);
        sysLoginService.snslogin(loginName,nickName);
        return ajaxResult;
    }

}
